package com.orion.config;

/**
 * @author Administrator
 * @date 2021/9/13
 */

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import com.orion.exception.VerfifyCodeException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 继承一个过滤器，实现验证码验证
 */
public class VerifyCodeFilter extends OncePerRequestFilter {

    private static final AntPathRequestMatcher ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/haha", HttpMethod.POST.name());

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        RequestMatcher.MatchResult matcher = ANT_PATH_REQUEST_MATCHER.matcher(httpServletRequest);
        if (matcher.isMatch()) {
            String errMsg = "";

            String inputVerifyCode = httpServletRequest.getParameter("verifyCode");

            if (StringUtils.isBlank(inputVerifyCode)) {
                errMsg = "验证码为空";
            } else {
                Object attrObj = httpServletRequest.getSession().getAttribute("verifyCode");
                if (Objects.isNull(attrObj) || attrObj.toString().isEmpty()) {
                    errMsg = "验证码已过期";
                } else {
                    String sessionVerifyCode = attrObj.toString();
                    if (!inputVerifyCode.equalsIgnoreCase(sessionVerifyCode)) {
                        errMsg = "验证码不正确";
                    }
                }
            }

            if (StringUtils.isNotBlank(errMsg)) {
                httpServletRequest.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new VerfifyCodeException(errMsg));
                httpServletResponse.sendRedirect("/myLogin?error");
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}


